

package cn.shengchao.examstar.teacher.acl.adapters.repositories;

import cn.shengchao.examstar.teacher.acl.ports.message.TeacherInfo;
import cn.shengchao.examstar.teacher.acl.ports.repositories.ITeacherRepository;
import cn.shengchao.examstar.teacher.infrastructure.dao.TeacherDao;
import cn.shengchao.examstar.teacher.infrastructure.dao.TeacherShowDao;
import cn.shengchao.examstar.teacher.infrastructure.dao.po.TTeacherShow;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

@Repository
public class TeacherRepository implements ITeacherRepository {

    @Autowired
    private TeacherDao teacherDao;

    @Autowired
    private TeacherShowDao teacherShowDao;

    @Override
    public List<TeacherInfo> findByIds(String[] ids) {
        if (ids.length > 0) {
            return teacherDao.selectBatchIds(Arrays.asList(ids)).stream().map(TeacherInfo::of).toList();
        } else {
            return List.of();
        }
    }

    @Override
    public TeacherInfo findById(Long teacherId) {
        return TeacherInfo.of(teacherDao.selectById(teacherId));
    }

    @Override
    public void updateShow(Long teacherId) {
        TTeacherShow tTeacherShow = teacherShowDao.selectOne(new LambdaQueryWrapper<TTeacherShow>()
                .eq(TTeacherShow::getTeacherId, teacherId));
        if (tTeacherShow == null) {
            tTeacherShow = new TTeacherShow();
            tTeacherShow.setTeacherId(teacherId);
            tTeacherShow.setSum(1L);
            teacherShowDao.insert(tTeacherShow);
        } else {
            tTeacherShow.setSum(tTeacherShow.getSum() + 1);
            teacherShowDao.updateById(tTeacherShow);
        }
    }

    @Override
    public Long getShowSum(Long teacherId) {
        TTeacherShow tTeacherShow = teacherShowDao.selectOne(new LambdaQueryWrapper<TTeacherShow>()
                .eq(TTeacherShow::getTeacherId, teacherId));
        return tTeacherShow == null ? 0L : tTeacherShow.getSum();
    }
}
